<?php

namespace addons\facrm\library\cloudcall\engine;


use fast\Http;

/**
 * Mycall
 * @author amplam 122795200@qq.com
 */
class Mycall extends Server
{
    /**
     * 测试的账号
     * @var array|string[]
     */
    protected $config = [
        'url' => '',
        'secret' => '',
    ];

    /**
     * 构造方法
     * @param $config
     */
    public function __construct($config = array())
    {
        $this->config = $config ? $config : $this->config;
    }

    /**
     * 拨打
     * @param $config
     * @param $data Exten
     * @param array $extend 扩展参数
     * @return bool
     */
    public function call($data = array(), $extend = array())
    {
        if (!isset($data['exten']) || !$data['exten']) {
            $this->error = '联系方式不能为空';
            return false;
        }
        if (!isset($data['from_exten']) || !$data['from_exten']) {
            $this->error = '坐席不能为空';
            return false;
        }
        $send_data = [
            'agentId' => $data['from_exten'],
            'called' => $data['exten'],
        ];
        $header = [
            'Content-Type: application/json; charset=utf-8',
            'Authorization: ' . $this->config['secret'],
            'Content-Length: ' . strlen(json_encode($send_data)),
        ];

        $url = $this->config['url'] . "/sendServer/ZkMv720P1r0atKur/agentCall";
        $result = self::curl_post_content($url, json_encode($send_data), $header);

        $result = json_decode($result, true);
        if (isset($result['code']) && $result['code'] == 200 && isset($result['data']['callId'])) {
            return ['ActionID' => $result['data']['callId']];
        }

        $this->error = isset($result['msg']) ? $result['msg'] : "呼叫失败";

        return false;
    }


    /**
     * 签入或签出
     */
    public function signInOrOut($data)
    {

        //sendServer/ZkMv720P1r0atKur/updateAgents

        $send_data = [
            'agentId' => $data['exten'],
            'status' => isset($data['sign']) ? $data['sign'] : 'Available',//上班=Available 下班=Logged Out
        ];
        $header = [
            'Content-Type: application/json; charset=utf-8',
            'Authorization: ' . $this->config['secret'],
            'Content-Length: ' . strlen(json_encode($send_data)),
        ];

        $url = $this->config['url'] . "/sendServer/ZkMv720P1r0atKur/updateAgents";

        return self::curl_post_content($url, json_encode($send_data), $header);


    }

    /**
     * 获取通话记录[无相关接口请配置通话回调]
     */
    public function getCallRecord($data)
    {

        return [];
    }


    /**
     * TODO【无相关接口，请根据事件回调自行分析】
     */
    public function statistics($data = array())
    {


    }


    public static function curl_post_content($url, $data = null, $header = [])
    {
        $ch = curl_init();
        if (substr_count($url, 'https://') > 0) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        }
        curl_setopt($ch, CURLOPT_URL, $url);
        if (!empty($data)) {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        if (!empty($header)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        }
        curl_setopt($ch, CURLOPT_TIMEOUT, 15);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
        $res = curl_exec($ch);
        if (curl_errno($ch)) {
            $res = false;
        }
        curl_close($ch);

        return $res;
    }


    /**
     * 通话结束回调
     */
    public function back()
    {

        $params = request()->getContent();
        \think\Log::write($params, "_________callcack________");
        $params = json_decode($params, true);

        $params = json_decode($params,true);//对方多转了一次

        $cloudcallLog = new \app\admin\model\facrm\CloudcallLog();
        $from_exten = "";
        $exten_type = "dialout";
        $params_data=[];

        if (isset($params['agentsId'])){
            //坐席弹屏 处理事务

            return $this->msg("200");
        }


        if (isset($params['callAgentTime'])) {
            //来电呼入坐席
            $from_exten = $params['called'];
            $exten_type = "normal";
            $params_data['call_time_length']=$this->callTimeLenth($params['agentAnswerTime'],$params['end']);
            $params_data['create_time']=isset($params['callAgentTime'])&&$params['callAgentTime']?strtotime($params['callAgentTime']):time();

        } else {
            //外呼结束回调
            $from_exten = $params['caller'];//坐席号？
            $params_data['call_time_length']=$params['talkTime'];
        }
        if ($params['callId']) {
            $log = $cloudcallLog->where('action_id', $params['callId'])->find();
            if ($log) {
                $params_data['status']=isset($params['callStatus']) && $params['callStatus'] == '0' ? 1 : -1;
                $params_data['called_no']= $log->called_no ? $log->called_no : $params['called'];//被叫
                $params_data['call_no']= $log->call_no ? $log->call_no : $params['caller'];//主叫
                $params_data['record_file']=$params['media'];
                $log->save($params_data);
                return $this->msg("200", $log->toArray());
            } else {
                $cloudcall = new \app\admin\model\facrm\Cloudcall();
                $admin_id = $cloudcall->where('cloud', "Callwg")->where('from_exten', $from_exten)->order('update_time desc')->value('admin_id');
                //添加记录
                $params_data['admin_id']=$admin_id ? $admin_id : 0;
                $params_data['cloud']='Callwg';
                $params_data['from_exten']=$from_exten;
                $params_data['exten_type']=$exten_type;
                $params_data['name']="";
                $params_data['source']='';
                $params_data['source_id']=0;
                $params_data['status']=isset($params['callStatus']) && $params['callStatus'] == '0' ? 1 : -1;

                $params_data['call_no']= $params['caller'] ? $params['caller'] : '';
                $params_data['called_no']= $params['called'] ? $params['called'] : '';
                $params_data['record_file']= $params['media'] ;
                $params_data['action_id']=  $params['callId'];
                $cloudcallLog->isUpdate(false)->save($params_data);
                return $this->msg("200", $params_data);
            }
        }


    }

    /**
     * 输出内容
     */
    protected function msg($msg = "200", $log = array())
    {
        echo $msg;
        hook('cloudcall_back', $log);
        exit();
    }
    /**
     * 获取通话时长
     * @param $start
     * @param $end
     * @return bool|string
     */
    protected function callTimeLenth($start, $end)
    {
        if (!$start || !$end) return 0;
        $start = is_numeric($start) ?: strtotime($start);
        $end = is_numeric($end) ? $end : strtotime($end);

        return \fast\Date::span($start, $end, 'seconds');
    }


}